#Deze wordt ge-extend, daardoor hoeft er nergens self. voor
#Dat doet 'ie vanzelf

# Get a metaclass for this class
#require 'metaid.rb'

require 'librmpd'
  

class MPD
  #Extra's om het leven wat aangenamer te maken (voor MPD)
  module Extras
    
    NEXT_SONG_CALLBACK = 13
    PREVIOUS_SONG_CALLBACK = 14
    END_OF_PLAYLIST_CALLBACK = 15
      
    def initialize_with_extras(*args)
      initialize_without_extras
    
      @callbacks[NEXT_SONG_CALLBACK] = []
      @callbacks[PREVIOUS_SONG_CALLBACK] = []
      @callbacks[END_OF_PLAYLIST_CALLBACK] = []
      
      #This requires a hack in librmpd...
      @callbacks[CURRENT_SONG_CALLBACK].unshift self.method('next_or_previous_callback')
    end
      
    def self.included(base)
      base.send(:extend, MPD::Extras::ClassMethods)
      base.send(:include, MPD::Extras::InstanceMethods)
      base.send(:alias_method_chain, :initialize, :extras)
    end
    
    private :initialize_with_extras
    
    module ClassMethods 
    end #ClassMethods
    
    module InstanceMethods
      
      def self.included(base)
      end
      
      def cb
        @callbacks
      end
    
      def diff_songs_from_current(i)
        begin
          current_pos = current_song.pos
          next_id = current_pos.to_i + i
        
          return nil if next_id < 0
        
          song_at_pos(next_id)
        rescue
          false
        end
      end
    
      def next?
        diff_songs_from_current 1
      end
    
      def previous?
        diff_songs_from_current(-1)
      end
    
      def next_or_previous_callback(current_song, previous_song)
        if previous_song == previous?
          for cb in @callbacks[NEXT_SONG_CALLBACK]
            cb.call(current_song)
          end
        else if previous_song == next?
            for cb in @callbacks[PREVIOUS_SONG_CALLBACK]
              cb.call(current_song)
            end
          end
        end
      end
      
      private :next_or_previous_callback
    
    end #InstanceMethods
    
  end #Extras
end #MPD